package com.fand.configuration.dao;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.joda.time.DateTime;

import com.fand.configuration.dto.VariableDto;
import com.fand.persistent.builder.ModelArgs;
import com.fand.persistent.builder.ModelBuilder;
import com.fand.persistent.builder.ModelBuilderUtils;
import com.fand.persistent.support.JdbcDaoSupport;
import com.google.common.collect.Maps;

/**
 * 变量
 * 
 * @author haitao.yao
 * 
 */
public class JdbcVariableDao extends JdbcDaoSupport implements VariableDao {
	@Override
	public String saveVariableBy1ForObject(final VariableDto variable) {
		final ModelBuilder selectModelBuilder = ModelBuilderUtils.newModelBuilder().putExtend(null, "code", null, variable.getCode());

		final VariableDto oldVariable = this.selectForMappedObject(VariableDto.class,
				"configuration/variable/selectVariableBy1ForMappedObjectList", selectModelBuilder.build());

		if (oldVariable == null) {
			final Date deginDaTi = new Date();
			final DateTime endDaTi = new DateTime(9999, 12, 31, 0, 0, 0, 0);

			variable.setBeginDaTi(deginDaTi);
			variable.setEndDaTi(endDaTi.toDate());
			variable.setId(UUID.randomUUID().toString());

			final ModelBuilder insertModelBuilder = ModelBuilderUtils.newModelBuilder(new ModelArgs(ModelBuilder.INSERT, variable));

			this.update("configuration/variable/insertVariableBy1", insertModelBuilder.build());

			return variable.getId();
		}

		do {
			if (!StringUtils.equals(oldVariable.getTypeId(), variable.getTypeId())) {
				break;
			}

			if (!StringUtils.equals(oldVariable.getName(), variable.getName())) {
				break;
			}

			if (!StringUtils.equals(oldVariable.getValue(), variable.getValue())) {
				break;
			}

			if (NumberUtils.compare(oldVariable.getOrderNum(), variable.getOrderNum()) != 0) {
				break;
			}

			return oldVariable.getId();
		} while (false);

		final ModelBuilder updateModelBuilder = ModelBuilderUtils.newModelBuilder(
				new ModelArgs(ModelBuilder.UPDATE, variable, "siteId", "typeId", "name", "value", "orderNum")).putExtend(null, "id",
				null, oldVariable.getId());

		this.update("configuration/variable/updateVariableBy1", updateModelBuilder.build());

		return oldVariable.getId();
	}

	@Override
	public List<VariableDto> selectVariableBy1ForMappedObjectList() {
		final Map<String, Object> model = Maps.newHashMap();

		return this.selectForMappedObjectList(VariableDto.class, "configuration/variable/selectVariableBy1ForMappedObjectList", model);
	}
}